#include <LiquidCrystal.h>

#define PIN_SENSOR A4
#define PIN_RS 10
#define PIN_EN 11
#define PIN_D4 2
#define PIN_D5 3
#define PIN_D6 8
#define PIN_D7 9
#define SAMPLING_RATE 100

static LiquidCrystal lcd(PIN_RS, PIN_EN, PIN_D4, PIN_D5, PIN_D6, PIN_D7);

static unsigned long sensorValue = 0;
static unsigned long sensorValueMax = 0;
static unsigned long sensorValueMin = 1023;

void setup()
{
  lcd.begin(16, 2);
  delay(1000);
}

void loop()
{
  for (int i = 0; i < SAMPLING_RATE; i++)
  {
    sensorValue = sensorValue + analogRead(PIN_SENSOR);
    delay(1000 / SAMPLING_RATE);
  }

  sensorValue = sensorValue / SAMPLING_RATE;

  if (sensorValue < sensorValueMin)
  {
    sensorValueMin = sensorValue;
  }

  if (sensorValue > sensorValueMax)
  {
    sensorValueMax = sensorValue;
  }

  lcd.setCursor(0, 0);
  lcd.print(map(sensorValue, min(sensorValueMin, 800), max(sensorValueMax, 936), 100, 0));
  lcd.print("%  ");

  lcd.setCursor(0, 1);
  lcd.print("[");
  lcd.print(sensorValue);
  lcd.print(", ");
  lcd.print(sensorValueMin);
  lcd.print(", ");
  lcd.print(sensorValueMax);
  lcd.print("]");
}
